#!/usr/bin/perl -w

$|++;

#yay for perl!
use GD;

use Data::Dumper;

foreach $i ( 1..1 ) {
	
	push(@files,"./images/image ($i).JPG");
	
}


my $resizeamount = 4;

my $threshold = 254;

foreach $filename ( @files ) {
	
	print "Processing: $filename\n";
	
	#load the image file
	my $image = GD::Image->new($filename);
	
	my ($width,$height) = $image->getBounds();
	
	print "Read image at " . $width . "x" . $height . "\n";
	
	#create a new blank image for the resize
	my $workimage = GD::Image->new(int($width/$resizeamount),int($height/$resizeamount));
	
	#do the resize
	$workimage->copyResized($image,0,0,0,0,int($width/$resizeamount),int($height/$resizeamount),$width,$height);
	
	#dispose of the original
	undef $image;
	
	#and swap in our reduced version
	$image = $workimage;
	
	#reset my width and height
	($width,$height) = $image->getBounds();
	
	print "Resized to " . $width . "x" . $height . "\n";
	
	print  " total colours detected : " . $image->colorsTotal() . "\n";
	
	print "checking " . ( $height * $width ) . " pixels\n";
	
	#create out clut histogram
	my @colours = ();
	
	#and fill it
	foreach $y ( 1..$height ) {
		
		foreach $x ( 1..$width ) {
			
			$colours[$image->getPixel($x,$y)]++;
			
		}
		
		if ( $y % 100 == 0 ) {
			
			print ".";
			
		}
		
	}
	
	print " done!\n";
	
	#now create our clut
	my @clut = ();
	
	#and populate it
	foreach $n ( 1..$image->colorsTotal() ) {
		
		@rgb = $image->rgb($n);
		
		push(@clut, [ @rgb ] );
		
	}
	
	print "clut poplated with " . @clut . " entries\n";
	
	
	#now do something with it
	
	
	print "finished\n";
	
}








sub average{
        my($data) = @_;
        if (not @$data) {
                die("Empty array\n");
        }
        my $total = 0;
        foreach (@$data) {
                $total += $_;
        }
        my $average = $total / @$data;
        return $average;
}
sub stdev{
        my($data) = @_;
        if(@$data == 1){
                return 0;
        }
        my $average = &average($data);
        my $sqtotal = 0;
        foreach(@$data) {
                $sqtotal += ($average-$_) ** 2;
        }
        my $std = ($sqtotal / (@$data-1)) ** 0.5;
        return ( $average , $std );
}







1;